package com.jxc.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.jxc.entity.TbMenu;
import com.jxc.entity.TbPermission;
import com.jxc.entity.TbPermissionRole;
import com.jxc.entity.TbRole;
import com.jxc.dao.EmployeeRoleDAO;
import com.jxc.dao.OpControlDAO;
import com.jxc.dao.OpDataBaseControlDAO;
import com.jxc.dao.PermissionDAO;
import com.jxc.dao.permissionrole;
import com.jxc.pojo.Menu;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @包名   com.jxc.imp
 * @文件名 OpControlImpl.java
 * @作者   mopzyqing
 * @创建日期 Jul 13, 2010
 * @版本 V 1.0
 */
public class OpControlImpl implements OpControlDAO{
	
	@Resource private permissionrole permissionRoleService;
	@Resource private OpDataBaseControlDAO opDataBaseControlImpl;
	@Resource private EmployeeRoleDAO employeeRole;
	@Resource private PermissionDAO permission;
	
	private static Map moduleArray = new HashMap();
	private static Map menuMap = new HashMap();
	private static int menuCount = 0;
	private static List<Integer> module = new ArrayList();
	
	private static Map opMap = new HashMap();
	//private static String menuJson = new String();
	
	public Boolean initOp(String op){
	try{	

		JSONObject opJson = JSONObject.fromObject(op.trim());
		int pageId = Integer.valueOf(opJson.getString("pageId"));
		String opString = opJson.getString("op").toString();
		int opMapIndex = pageId;
		
		//作用：使得opMap与数据库一致
		if(opMap.get(opMapIndex)==null){
			//判断数据库中是否有
			List opList = permission.getPermissionByMuneId(pageId);
			if(opList.size()==0){
				//添加到数据库
				String opStringArray[] = opString.split(",");
				TbPermission tbPermission =new TbPermission();
				TbMenu menu = new TbMenu();
				menu.setMenuId(pageId);
				tbPermission.setTbMenu(menu);
				for(int i=0;i<opStringArray.length;i++){
					tbPermission.setOpName(opStringArray[i]);
					opDataBaseControlImpl.saveTbPermission(tbPermission);
				}
				opMap.put(opMapIndex, opJson);
			}else{
				//如果有的话，就初始化为数据库的
				String opDateBase = "";
				for(int i=0;i<opList.size();i++){
					TbPermission tbPermission = (TbPermission)opList.get(i);
					if(i==0){
						opDateBase = tbPermission.getOpName();
					}else{
						opDateBase = opDateBase+","+tbPermission.getOpName();
					}
				}
				opMap.put(opMapIndex, opDateBase.trim());
			}
		}
		if(!opMap.get(opMapIndex).toString().equals(opString)){
			//更新:删除页面所有的权限，插入所有权限
			
			List opList = permission.getPermissionByMuneId(pageId);

			String opStringArray[] = opString.split(",");
			//添加到数据库
			List<Integer> flatOpID = new ArrayList();
			
			for(int i=0;i<opStringArray.length;i++){
					
				boolean flat=true;
				for(int ii=0;ii<opList.size();ii++){
					TbPermission tbPermission = (TbPermission)opList.get(ii);
					if(tbPermission.getOpName().equals(opStringArray[i])){
						//添加
						flat=false;
						flatOpID.add(ii);//第ii个不删除
						break;
					}
				}
				if(flat){
					//保存
					TbPermission tbPermission = new TbPermission();
					tbPermission.setOpName(opStringArray[i]);
					TbMenu tbMenu=new TbMenu();
					tbMenu.setMenuId(pageId);
					tbPermission.setTbMenu(tbMenu);
					opDataBaseControlImpl.saveTbPermission(tbPermission);
				}
			}
			for(int i=0;i<opList.size();i++){
				
				if(flatOpID.indexOf(i)==-1){
					TbPermission tbPermission = (TbPermission)opList.get(i);
					//删除
					permission.deletePermissionById(tbPermission.getOpId());
				}
			}
			opMap.put(opMapIndex, opJson);
		}
	}catch(Exception e){
		e.printStackTrace();
		return false;
	}
	return true;
	}

	/**
	 * 
	 */
	public Boolean saveOrUpdateMenu(JSONObject jsonObj){
		
         String menu  = jsonObj.getString("name").trim();
         String iconCls  = jsonObj.getString("iconCls").trim();
         int menuIndex = Integer.valueOf(jsonObj.getString("orderby").trim());
		//菜单名称在menuMap中是否存在
        if(menuMap.get(menuIndex)==null){
       	 List menuParamis = permissionRoleService.QueryMenu(menuIndex);
       	 if(menuParamis.size()==0){//菜单在数据库中是否存在，不存在的话就保存到数据库中
       		 TbMenu menuObj = new TbMenu();
       		 menuObj.setMenuName(menu);
       		 menuObj.setOrderby(menuIndex);
       		 menuObj.setParentId(0);
       		 menuObj.setIsMenu(1);
       		 menuObj.setMenuIcon(iconCls);
       		 permissionRoleService.saveMenu(menuObj);
       	 }else{
       		 TbMenu menuUpdateObj = (TbMenu)menuParamis.get(0);
       		 
       		 TbMenu menuObj = new TbMenu();
      		 menuObj.setMenuName(menu);
      		 menuObj.setOrderby(menuIndex);
      		 menuObj.setParentId(0);
      		 menuObj.setIsMenu(1);
      		 menuObj.setMenuIcon(iconCls);
      		 menuObj.setMenuId(menuUpdateObj.getMenuId());
      		 menuObj.setTbPermission(menuUpdateObj.getTbPermission());
      		// menuObj.setTbPermissionRoles(menuUpdateObj.getTbPermissionRoles());
      		 
      		 boolean f = menuObj.getMenuName().equals(menuUpdateObj.getMenuName());
      		boolean f1 =menuObj.getOrderby().equals(menuUpdateObj.getOrderby());
      		boolean f2 = menuObj.getParentId().equals( menuUpdateObj.getParentId());
      		boolean f3 = menuObj.getIsMenu().equals(menuUpdateObj.getIsMenu());
      		boolean f4 = menuObj.getMenuIcon().equals(menuUpdateObj.getMenuIcon());
      		boolean f5 = menuObj.getMenuId().equals(menuUpdateObj.getMenuId());
      		
      		 if(!(f&&f1&&f2&&f3&&f4&&f5)){//判断对象是否由变化
	       		 menuUpdateObj.setMenuName(menu);
	       		 menuUpdateObj.setOrderby(menuIndex);
	       		 menuUpdateObj.setParentId(0);
	       		 menuUpdateObj.setIsMenu(1);
	       		 menuUpdateObj.setMenuIcon(iconCls);
	       		 //更新--------------------------------------
		       	permissionRoleService.updateMenu(menuUpdateObj);
      		 }
       	 }
       	menuMap.put(menuIndex, jsonObj);
        }else if(!menuMap.get(menuIndex).equals(jsonObj)){//菜单存在且有变化的情况下，更新菜单
        	 TbMenu menuObj = (TbMenu)permissionRoleService.QueryMenu(menuIndex).get(0);
      		 menuObj.setMenuName(menu);
      		 menuObj.setOrderby(menuIndex);
      		 menuObj.setParentId(0);
      		 menuObj.setIsMenu(1);
      		 menuObj.setMenuIcon(iconCls);
   		 //更新--------------------------------------
      		permissionRoleService.updateMenu(menuObj);
      		menuMap.put(menuIndex, jsonObj);
    }

		 return true;
	}
	/**
	 * 
	 */
	public void saveOrUpdatemodule(JSONObject jsonObj){
		
		 String module = jsonObj.getString("name").trim();
		 String url = jsonObj.getString("url").trim();
		 String iconCls  = jsonObj.getString("iconCls").trim();
		 int moduleIndex = Integer.valueOf(jsonObj.getString("orderby").trim());
		 int ParentOrderby = Integer.valueOf(jsonObj.getString("ParentOrderby").trim());
		 String moduleArrayIndex = ""+moduleIndex+","+ParentOrderby;//----------------
		//菜单名称在menuMap中是否存在
	        if(moduleArray.get(moduleArrayIndex)==null){
	        
	         List ParentList = permissionRoleService.QueryMenu(ParentOrderby);
	       	 int ParentId = Integer.valueOf(((TbMenu)ParentList.get(0)).getMenuId());
	       	 List moduleParamis = permissionRoleService.QueryMenu2(moduleIndex,ParentId); 
	       	 if(moduleParamis.size()==0){//菜单在数据库中是否存在，不存在的话就保存到数据库中 	       		 
	       		 TbMenu menuObj = new TbMenu();
	       		 menuObj.setMenuName(module);
	       		 menuObj.setOrderby(moduleIndex);
	       		 menuObj.setParentId(ParentId);
	       		 menuObj.setMenuParam(url);
	       		 menuObj.setIsMenu(1);
	       		 menuObj.setMenuIcon(iconCls);
	       		 permissionRoleService.saveMenu(menuObj);
	       	 }else{//菜单有在数据库中，但是有变化的情况
	       		
	       		 TbMenu menuUpdateObj = (TbMenu)moduleParamis.get(0);
	       		 TbMenu menuObj = new TbMenu();
	       		 menuObj.setMenuName(module);
	       		 menuObj.setOrderby(moduleIndex);
	       		 menuObj.setParentId(ParentId);
	       		 menuObj.setMenuParam(url);
	       		 menuObj.setIsMenu(1);
	       		 menuObj.setMenuIcon(iconCls);
	       		 menuObj.setMenuId(menuUpdateObj.getMenuId());
	       		 
	       		 if(!menuObj.equals(menuUpdateObj)){//判断对象是否由变化
		       		 menuUpdateObj.setMenuName(module);
		       		 menuUpdateObj.setOrderby(moduleIndex);
		       		 menuUpdateObj.setParentId(ParentId);
		       		 menuUpdateObj.setMenuParam(url);
		       		 menuUpdateObj.setIsMenu(1);
		       		 menuUpdateObj.setMenuIcon(iconCls);
		       		 //更新--------------------------------------
			       	permissionRoleService.updateMenu(menuUpdateObj);
	       		 }
	       	 }
	       	moduleArray.put(moduleArrayIndex, jsonObj);
	        }else if(!moduleArray.get(moduleArrayIndex).equals(jsonObj)){//子菜单存在且有变化的情况下，更新子菜单
	        	 List ParentList = permissionRoleService.QueryMenu(ParentOrderby);
		       	 int ParentId = Integer.valueOf(((TbMenu)ParentList.get(0)).getMenuId());
		       	 List moduleParamis = permissionRoleService.QueryMenu2(moduleIndex,ParentId); 
		       	 TbMenu menuObj = (TbMenu)moduleParamis.get(0);
	       		 menuObj.setMenuName(module);
	       		 menuObj.setOrderby(moduleIndex);
	       		 menuObj.setParentId(ParentId);
	       		 menuObj.setMenuParam(url);
	       		 menuObj.setIsMenu(1);
	       		 menuObj.setMenuIcon(iconCls);
	       		 //更新--------------------------------------
	       		permissionRoleService.updateMenu(menuObj);
	       		moduleArray.put(moduleArrayIndex, jsonObj);
	        }
	}
	/**
	 * 
	 * 
	 */
	public boolean initMenu(String json,int nowmenucount,String moduleIndexCountAllArray[]){
		
		try{
			if(menuCount==0){
				
				menuCount = permissionRoleService.QueryMenuCount();
			}
			if(menuCount>nowmenucount){//判断菜单总数是否有变化
				//删除多余菜单和旗下的子菜单
				//对父菜单ID进行分组，获取父菜单ID和子菜单的总个数，然后对module初始化
				List ParentList = permissionRoleService.QueryMenuBig((nowmenucount-1));
				for(int i=0;i<ParentList.size();i++){
					int ParentId = Integer.valueOf(((TbMenu)ParentList.get(i)).getMenuId());
					permissionRoleService.deleteMenuSub(ParentId);//删除父节点中相应的子菜单
				}
				permissionRoleService.deleteMenuByOrderby((nowmenucount-1));//删除菜单
				
				menuCount=nowmenucount;//对内存中的菜单数进行更新
				moduleArray.clear();//对子菜单重新构造
				menuMap.clear();//对菜单重新构造
			}
			for(int i=0;i<menuCount;i++){
				
				if(module.size()!=menuCount){
					module.clear();
					//对父菜单ID进行分组，获取父菜单ID和子菜单的总个数，然后对module重新初始化
					for(int ii=module.size();ii<menuCount;ii++){
						List ParentList = permissionRoleService.QueryMenu(ii);
						int ParentId = Integer.valueOf(((TbMenu)ParentList.get(0)).getMenuId());
						int OneMenuModuleCount = permissionRoleService.QueryMenuIDandSubCount(ParentId);
						module.add(ii, OneMenuModuleCount);
					}
				}
				int moduleIndexCount = Integer.valueOf(moduleIndexCountAllArray[i].trim());
				if(module.get(i)>moduleIndexCount){
					//删除子菜单
					List ParentList = permissionRoleService.QueryMenu(i);
					int ParentId = Integer.valueOf(((TbMenu)ParentList.get(0)).getMenuId());
					permissionRoleService.deleteMenuSubByOrderby(ParentId,(moduleIndexCount-1));
					module.add(i,moduleIndexCount);//更新module（内存）中的子菜单个数
					moduleArray.clear();//对子菜单重新构造
				}
			}
			
			JSONArray jsonArray = JSONArray.fromObject(json);
			for (int i = 0; i < jsonArray.size(); i++) {
				Object o = jsonArray.get(i);
				JSONArray jsonArray2 = JSONArray.fromObject(o);
				
				for (int ii = 0; ii < jsonArray2.size(); ii++){
					Object o2 = jsonArray2.get(ii);
					JSONObject jsonObject = JSONObject.fromObject(o2);
					
					if(jsonObject.getString("url").equals("")){
					
						saveOrUpdateMenu(jsonObject);
					}
				}

				for (int ii = 0; ii < jsonArray2.size(); ii++){
					Object o2 = jsonArray2.get(ii);
					JSONObject jsonObject = JSONObject.fromObject(o2);
					if(jsonObject.getString("url").equals("")){
						
					}else{
						
							saveOrUpdatemodule(jsonObject);
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public boolean initRolePo(TbRole tbRole){
		
		List<TbMenu> list = opDataBaseControlImpl.QueryMenu();
		List<TbPermissionRole> tbPermissionRole = new ArrayList();
		for(int i=0;i<list.size();i++){
			
			TbPermissionRole permissionRole = new TbPermissionRole();
			//permissionRole.setOpId(0);
			//permissionRole.setOpValue(0);
			//permissionRole.setTbMenu(list.get(i));
			permissionRole.setTbRole(tbRole);
		}
		boolean flat = opDataBaseControlImpl.initRole(tbPermissionRole);
		return flat;
	}
	//用户菜单权限控制
	public List initIndexPage(int employeeID){
		
		List roleidList = employeeRole.QueryRoleIDByEmployeeid(employeeID);
		String tj = "";
		for(int i=0;i<roleidList.size();i++){

			if(i==0){
				tj = tj + " tbRole.roleId=" +roleidList.get(i);
			}else{
				tj = tj + " or tbRole.roleId=" +roleidList.get(i);
			}
		}
		List<Object[]> tbMenuList = opDataBaseControlImpl.QueryTbPermissionRole(tj);
		List initList = new ArrayList();
		for(Object[] object : tbMenuList){
			
			if(Integer.valueOf(object[2].toString())==0)
			{
				List menuList = new ArrayList();
				String iconCls = object[5].toString();
				String name = object[1].toString();
				String url = "";
				int orderby = Integer.valueOf(object[4].toString());
				int id = Integer.valueOf(object[0].toString());
				Menu menu = new Menu();
				menu.setIconCls(iconCls);
				menu.setName(name);
				menu.setUrl(url);
				menu.setOrderby(orderby);
				menu.setId(id);
				menuList.add(menu);
				initList.add(menuList);
			}
		}
		for(int i=0;i<initList.size();i++){
			
			List muneList = (List)initList.get(i);
			Menu menu = (Menu)(muneList).get(0);
			int menuID = menu.getId();
			for(Object[] obj2 : tbMenuList){
				int parentId = Integer.valueOf(obj2[2].toString());
				if(menuID ==parentId){
					String iconCls = obj2[5].toString();
					String name = obj2[1].toString();
					String url = obj2[3].toString()+"?pageId="+obj2[0].toString();
					int orderby = Integer.valueOf(obj2[4].toString());
					int id = Integer.valueOf(obj2[0].toString());
					Menu menuSub = new Menu();
					menuSub.setIconCls(iconCls);
					menuSub.setName(name);
					menuSub.setUrl(url);
					menuSub.setOrderby(orderby);
					menuSub.setId(id);
					muneList.add(menuSub);
				}
			}
		}
		return initList;
	}
}
